package com.sqlcheck.dto.response;

import com.sqlcheck.entity.ScanResult;
import lombok.Builder;
import lombok.Data;

import java.util.Map;

@Data
@Builder
public class ScanResultVO {
    // AI置信度阈值常量
    public static final double AI_CONFIDENCE_THRESHOLD = 0.7;
    
    // 基本问题信息
    private String ruleId;
    private String ruleName;
    private IssueTypeEnum issueType; // 使用枚举替代字符串
    private SeverityEnum severity; // 使用枚举替代字符串
    private String description;
    private String suggestion;

    // SQL相关信息
    private String sqlContent;
    private String originalSql;
    private String suggestedSql;

    // 位置信息
    private String sourceFile;
    private String fileName;
    private Integer lineNumber;
    private Integer columnNumber;
    private Integer statementNumber;
    private String gitFileUrl;

    // AI增强验证字段
    private Boolean ruleAnalysisConfirmed;
    private String aiIssueDescription;
    private Double aiConfidenceScore;
    private String optimizedSql;
    private String optimizationExplanation;
    private AnalysisEngineEnum analysisEngine; // 使用枚举
    private Boolean aiOptimized;
    private Map<String, Object> aiVerificationDetails;

    // 便捷方法
    public static ScanResultVO fromScanResult(ScanResult scanResult) {
        if (scanResult == null) {
            return null;
        }

        ScanResultVOBuilder builder = ScanResultVO.builder()
                .ruleId(scanResult.getRuleId())
                .ruleName(scanResult.getRuleName())
                .issueType(IssueTypeEnum.fromScanResultIssueType(scanResult.getIssueType()))
                .severity(SeverityEnum.fromScanResultSeverity(scanResult.getSeverity()))
                .description(scanResult.getIssueDescription())
                .suggestion(scanResult.getSuggestion())
                .sqlContent(scanResult.getSqlContent())
                .originalSql(scanResult.getOriginalSql())
                .suggestedSql(scanResult.getSuggestedSql())
                .lineNumber(scanResult.getLineNumber())
                .columnNumber(scanResult.getColumnNumber())
                .statementNumber(scanResult.getStatementNumber())
                .ruleAnalysisConfirmed(scanResult.getRuleAnalysisConfirmed())
                .aiIssueDescription(scanResult.getAiIssueDescription())
                .optimizedSql(scanResult.getOptimizedSql())
                .optimizationExplanation(scanResult.getOptimizationExplanation())
                .aiOptimized(scanResult.getAiOptimized())
                .aiVerificationDetails(scanResult.getAiVerificationDetails());

        // 处理aiConfidenceScore转换
        if (scanResult.getAiConfidenceScore() != null) {
            builder.aiConfidenceScore(scanResult.getAiConfidenceScore().doubleValue());
        }

        // 处理analysisEngine
        if (scanResult.getAnalysisEngine() != null) {
            builder.analysisEngine(AnalysisEngineEnum.fromString(scanResult.getAnalysisEngine()));
        }

        // 处理文件信息
        String filePath = scanResult.getFilePath();
        builder.sourceFile(filePath);
        
        // 提取文件名
        if (filePath != null && !filePath.isEmpty()) {
            String fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
            builder.fileName(fileName);
        }
        
        // 从metadata中获取动态生成的gitFileUrl
        Map<String, Object> metadata = scanResult.getMetadata();
        if (metadata != null) {
            builder.gitFileUrl((String) metadata.get("gitFileUrl"));
        }

        return builder.build();
    }

    public boolean isAiVerified() {
        return aiOptimized != null && aiOptimized;
    }

    public boolean isRuleConfirmedByAI() {
        // 基于aiOptimized和置信度判断AI确认状态
        // 只有经过AI优化且置信度>=阈值才认为是AI确认
        return aiOptimized != null && aiOptimized && aiConfidenceScore != null && aiConfidenceScore >= AI_CONFIDENCE_THRESHOLD;
    }

    public boolean isRuleQuestionedByAI() {
        // 基于aiOptimized和置信度判断AI质疑状态
        // 经过AI优化但置信度<阈值认为是AI质疑
        return aiOptimized != null && aiOptimized && (aiConfidenceScore == null || aiConfidenceScore < AI_CONFIDENCE_THRESHOLD);
    }

    public Integer getConfidencePercent() {
        return aiConfidenceScore != null ? (int) (aiConfidenceScore * 100) : null;
    }

    // 枚举定义
    public enum IssueTypeEnum {
        SYNTAX_ERROR("语法错误"),
        COMPATIBILITY_WARNING("兼容性警告"),
        PERFORMANCE_ISSUE("性能问题"),
        SECURITY_RISK("安全风险");

        private final String description;

        IssueTypeEnum(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }

        public static IssueTypeEnum fromScanResultIssueType(ScanResult.IssueType issueType) {
            if (issueType == null)
                return null;
            return valueOf(issueType.name());
        }
    }

    public enum SeverityEnum {
        HIGH("高"), MEDIUM("中"), LOW("低"), INFO("信息");

        private final String description;

        SeverityEnum(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }

        public static SeverityEnum fromScanResultSeverity(ScanResult.Severity severity) {
            if (severity == null)
                return null;
            return valueOf(severity.name());
        }
    }

    public enum AnalysisEngineEnum {
        RULE("规则引擎"),
        RULE_WITH_AI_ENHANCEMENT("规则引擎+AI增强");

        private final String description;

        AnalysisEngineEnum(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }

        public static AnalysisEngineEnum fromString(String engineStr) {
            if (engineStr == null)
                return null;
            switch (engineStr.toUpperCase()) {
                case "RULE":
                    return RULE;
                case "AI":
                case "RULE_WITH_AI_ENHANCEMENT":
                    return RULE_WITH_AI_ENHANCEMENT;
                default:
                    return RULE;
            }
        }
    }
}